package day06;

/**
 * @author zouran
 * createDate：2024/6/29  14:51
 */
class SyncThread extends Thread {
    private int count;

    public SyncThread() {
        count = 0;
    }

    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName() + "Start");
        synchronized (this) {
            for (int i = 0; i < 2; i++) {
                System.out.println(Thread.currentThread().getName() + ":" + (++count));
            }
        }
        System.out.println(Thread.currentThread().getName() + "End");
    }
}

class SyncThread2 extends Thread {
    private int count;

    public SyncThread2() {
        count = 0;
    }

    /*public synchronized void addCount(){
        System.out.println(Thread.currentThread().getName() + ":" + (++count));
    }*/
    public void addCount() {
        synchronized (this) {
            System.out.println(Thread.currentThread().getName() + ":" + (++count));
        }
    }

    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName() + "Start");
        for (int i = 0; i < 2; i++) {
            this.addCount();
        }
        System.out.println(Thread.currentThread().getName() + "End");
    }
}

class SyncThread3 extends Thread {
    private static int count;

    public SyncThread3() {
        count = 0;
    }

    public static synchronized void addCount() {
        System.out.println(Thread.currentThread().getName() + ":" + (++count));
    }

    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName() + "Start");
        for (int i = 0; i < 2; i++) {
            addCount();
        }
        System.out.println(Thread.currentThread().getName() + "End");
    }
}

class SyncThread4 extends Thread {
    private static int count;

    public SyncThread4() {
        count = 0;
    }

    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName() + "Start");
        synchronized (SyncThread4.class) {
            for (int i = 0; i < 2; i++) {
                System.out.println(Thread.currentThread().getName() + ":" + (++count));
            }
        }
        System.out.println(Thread.currentThread().getName() + "End");
    }
}

public class synchronizedMain {
    public static void main(String[] args) {
        SyncThread4 s1 = new SyncThread4();
        SyncThread4 s2 = new SyncThread4();
        Thread t1 = new Thread(s1);
        Thread t2 = new Thread(s2);
        t1.start();
        t2.start();
    }
}
